<template>
  <div class="box1">

    <!-- 上部分视频合作 -->
    <div class="videoBox"
         v-loading="loading"
         element-loading-text="等待对方接通"
         element-loading-spinner="el-icon-loading"
         element-loading-background="rgba(0, 0, 0, 0.8)">
      <div class="localViewBox"
           id="localview"></div>
      <div class="remoteViewBox"
           id="remoteview"></div>
    </div>
    <div class="btnBox">
      <span class="iconfont icon-laba"
            :class="btnaudio?'selected':''"
            @click="switchAudio()"></span>
      <span class="iconfont icon-shexiangtou"
            :class="btnvideo?'selected':''"
            @click="switchCamera()"></span>
      <span class="iconfont icon-dianhua01"
            :class="btnend?'selected':''"
            @click="switchLogingOrOut()"></span>
    </div>

    <!-- 来电弹窗 -->
    <el-dialog title="来电提示"
               :visible.sync="callDialog"
               width="30%"
               append-to-body>
      <span>来自{{sponsor}}的电话</span>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="callDialog = false;rejectCall()">拒接</el-button>
        <el-button type="primary"
                   @click="callDialog = false,acceptCall()">接听</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import LibGenerateTestUserSig from '../assets/js/lib-generate-test-usersig.min.js'

import TRTCCalling from 'trtc-calling-js'

const options = {
  SDKAppID: 1400498533 // 接入时需要将0替换为您的云通信应用的 SDKAppID
}
const trtcCalling = new TRTCCalling(options)

export default {
  name: 'MyTRTC',
  props: ['userID', 'toUserID'],
  data () {
    return {
      callDialog: false, // 弹窗是否显示
      inviteID: '',
      inviteData: '',
      callType: '',
      sponsor: '',
      invitedUserID: {},
      btnvideo: false, // 视频按钮
      btnaudio: false, // 音频按钮
      btnend: false, // 挂断
      loading: false, // 加载
      isStartLocalView: false
    }
  },
  created () {
    this.startInit()
  },
  destroyed () {
    console.log('rtc组件销毁了')
    this.logout()
  },
  methods: {
    switchCamera () {
      if (this.btnvideo) trtcCalling.closeCamera()
      else trtcCalling.openCamera()
      this.btnvideo = !this.btnvideo
    },
    switchAudio () {
      trtcCalling.setMicMute(this.btnaudio) // 开启麦克风
      this.btnaudio = !this.btnaudio
    },
    switchLogingOrOut () {
      if (!this.btnend) this.startCall()
      else this.logout()
      this.btnend = !this.btnend
    },
    // 获取用户签名--前端测试用
    genTestUserSig (userID) {
      const SDKAPPID = 1400498533

      const EXPIRETIME = 604800

      const SECRETKEY =
        '704d2bdcfd237012c230047ec9356311311db2c9b21b4b176931d2bcbc62356e'
      if (SDKAPPID === '' || SECRETKEY === '') {
        alert(
          '请先配置好您的账号信息： SDKAPPID 及 SECRETKEY ' +
          '\r\n\r\nPlease configure your SDKAPPID/SECRETKEY in js/debug/GenerateTestUserSig.js'
        )
      }
      const generator = new LibGenerateTestUserSig(SDKAPPID, SECRETKEY, EXPIRETIME)
      const userSig = generator.genTestUserSig(userID)
      return {
        sdkAppId: SDKAPPID,
        userSig: userSig
      }
    },
    startInit () {
      // 初始化一些参数
      this.btnvideo = false
      this.btnaudio = false
      this.btnend = false
      // 初始化监听器
      this.initListener()
      const userID = this.userID
      const config = this.genTestUserSig(this.userID)
      const userSig = config.userSig
      // 登录服务器
      trtcCalling.login({
        userID,
        userSig
      })
    },
    // 初始化监听器
    initListener () {
      // sdk内部发生了错误
      trtcCalling.on(TRTCCalling.EVENT.ERROR, this.handleError)
      // 被邀请进行通话
      trtcCalling.on(TRTCCalling.EVENT.INVITED, this.handleNewInvitationReceived)
      // 有用户同意进入通话，那么会收到此回调
      trtcCalling.on(TRTCCalling.EVENT.USER_ENTER, this.handleUserEnter)
      // 如果有用户同意离开通话，那么会收到此回调
      trtcCalling.on(TRTCCalling.EVENT.USER_LEAVE, this.handleUserLeave)
      // 用户拒绝通话
      trtcCalling.on(TRTCCalling.EVENT.REJECT, this.handleInviteeReject)
      // 邀请方忙线
      trtcCalling.on(TRTCCalling.EVENT.LINE_BUSY, this.handleInviteeLineBusy)
      // 作为被邀请方会收到，收到该回调说明本次通话被取消了
      trtcCalling.on(TRTCCalling.EVENT.CALLING_CANCEL, this.handleInviterCancel)
      // 重复登陆，收到该回调说明被踢出房间
      trtcCalling.on(TRTCCalling.EVENT.KICKED_OUT, this.handleKickedOut)
      // 作为邀请方会收到，收到该回调说明本次通话超时未应答
      trtcCalling.on(TRTCCalling.EVENT.CALLING_TIMEOUT, this.handleCallTimeout)
      // 邀请用户无应答
      trtcCalling.on(TRTCCalling.EVENT.NO_RESP, this.handleNoResponse)
      // 收到该回调说明本次通话结束了
      trtcCalling.on(TRTCCalling.EVENT.CALLING_END, this.handleCallEnd)
      // 远端用户开启/关闭了摄像头, 会收到该回调
      trtcCalling.on(TRTCCalling.EVENT.USER_VIDEO_AVAILABLE, this.handleUserVideoChange)
      // 远端用户开启/关闭了麦克风, 会收到该回调
      trtcCalling.on(TRTCCalling.EVENT.USER_AUDIO_AVAILABLE, this.handleUserAudioChange)
    },
    // 移除监听器
    removeListener () {
      trtcCalling.off(TRTCCalling.EVENT.ERROR, this.handleError)
      trtcCalling.off(TRTCCalling.EVENT.INVITED, this.handleNewInvitationReceived)
      trtcCalling.off(TRTCCalling.EVENT.USER_ENTER, this.handleUserEnter)
      trtcCalling.off(TRTCCalling.EVENT.USER_LEAVE, this.handleUserLeave)
      trtcCalling.off(TRTCCalling.EVENT.REJECT, this.handleInviteeReject)
      trtcCalling.off(TRTCCalling.EVENT.LINE_BUSY, this.handleInviteeLineBusy)
      trtcCalling.off(TRTCCalling.EVENT.CALLING_CANCEL, this.handleInviterCancel)
      trtcCalling.off(TRTCCalling.EVENT.KICKED_OUT, this.handleKickedOut)
      trtcCalling.off(TRTCCalling.EVENT.CALLING_TIMEOUT, this.handleCallTimeout)
      trtcCalling.off(TRTCCalling.EVENT.NO_RESP, this.handleNoResponse)
      trtcCalling.off(TRTCCalling.EVENT.CALLING_END, this.handleCallEnd)
      trtcCalling.off(TRTCCalling.EVENT.USER_VIDEO_AVAILABLE, this.handleUserVideoChange)
      trtcCalling.off(TRTCCalling.EVENT.USER_AUDIO_AVAILABLE, this.handleUserAudioChange)
    },
    // 呼叫对方
    startCall () {
      trtcCalling.call({ userID: this.toUserID, type: 2, timeout: 10 })
      this.loading = true
    },
    // 接受一个电话
    acceptCall () {
      this.loading = true
      trtcCalling.accept({
        inviteID: this.inviteID,
        roomID: this.inviteData.roomID,
        callType: this.inviteData.callType
      })
    },
    // 拒绝一个电话
    rejectCall () {
      trtcCalling.reject({ inviteID: this.inviteID, isBusy: true, callType: this.callType })
    },

    // 处理错误
    handleError () { },
    // 收到了邀请通知
    handleNewInvitationReceived (payload) {
      const { inviteID, sponsor, inviteData, userIDList } = payload
      this.inviteID = inviteID
      this.inviteData = inviteData
      this.callType = inviteData.callType
      this.sponsor = sponsor
      this.invitedUserID = JSON.parse(JSON.stringify(userIDList))// 被邀请者

      // this.loading = true
      this.callDialog = true
    },
    // 建立连接
    handleUserEnter ({ userID }) {
      this.$message.success(userID + '进入房间')
      this.btnvideo = true
      this.btnaudio = true
      this.btnend = true
      // 将loading去掉
      this.loading = false
      // 开启视频渲染
      this.startLocalView()
      this.startRemoteView(userID)
    },
    // 用户退出房间
    handleUserLeave ({ userID }) {
      this.$message.success('对方已经离线')
      // this.logout()
      // 向父级容器发送相关通知
      this.$emit('endCall')
    },
    // 被邀请用户拒绝通话
    handleInviteeReject ({ userID }) {
      this.btnend = false
      this.btnvideo = false
      this.btnaudio = false
      this.$message.success(userID + '对方拒绝通话')
      this.$emit('endCall')
      // this.logout()
    },
    // 通知呼叫方，对方在忙碌，未接通
    handleInviteeLineBusy ({ sponsor, userID }) {
      // A call B,C call A, A在忙线， 拒绝通话，对于呼叫者C收到通知，XXX在忙线
      if (sponsor === this.userID) {
        this.$message.success('对方忙碌')
        // this.logout()
      }
    },
    // 通知被呼叫方，邀请被取消，未接通
    handleInviterCancel () {
      this.$message.success('邀请被取消')
      this.$emit('endCall')
      // this.logout()
    },
    handleKickedOut () {
      this.$message.error('重复登录')
      // this.logout()
      this.$emit('endCall')
    },
    handleCallTimeout ({ userIDList }) {
      this.$message.error('超时')
      this.logout()
      this.$emit('endCall')
    },
    // 自己超时且是邀请发起者，需主动挂断，并通知上层对端无应答
    handleNoResponse ({ sponsor, userIDList }) { // 邀请者
      // this.logout()
      this.$message.success('对方无响应')
      this.$emit('endCall')
    },
    // 双方，通话已建立, 通话结束
    handleCallEnd ({ userID, callEnd }) {
      // this.logout()
      this.btnend = false
      this.btnvideo = false
      this.btnaudio = false
      this.$message.success('通话结束')
      this.$emit('endCall')
    },
    handleUserVideoChange () {

    },
    handleUserAudioChange (payload) {
    },
    logout () {
      // 挂掉电话
      this.callDialog = false
      this.btnaudio = false
      this.btnvideo = false
      this.btnend = false
      trtcCalling.hangup()
      this.$emit('endCall')
    },
    // 播放本地流
    startLocalView () {
      trtcCalling.startLocalView({
        userID: this.userID,
        videoViewDomID: 'localview'
      }).then(() => {
        this.isStartLocalView = true
      })
    },
    //
    // 播放远端流
    startRemoteView (userID) {
      trtcCalling.startRemoteView({
        userID: userID,
        videoViewDomID: 'remoteview'
      }).then(() => {

      })
    }
  }
}
</script>
<style lang="less" scoped>
.box1 {
  width: 100%;
  height: 100%;
  .videoBox {
    width: 100%;
    height: 500px;

    .localViewBox {
      width: 50%;
      height: 100%;
      float: left;
      background-color: rgba(243, 248, 238, 0.466);
      border: 1px solid rgba(255, 255, 255, 0.308);
    }

    .remoteViewBox {
      width: 50%;
      height: 100%;
      float: left;
      background-color: rgba(243, 248, 238, 0.466);
      border: 1px solid rgba(255, 255, 255, 0.308);
    }
  }
  .btnBox {
    width: 100%;
    height: 100px;
    background-color: rgb(255, 255, 255);

    display: flex;
    justify-content: center;
    align-items: center;

    span {
      font-size: 30px;
      margin: 0 20px;
      cursor: pointer;
    }

    span:hover {
      color: rgb(109, 159, 235);
    }

    .selected {
      color: rgb(109, 159, 235);
    }
  }
}
</style>
